package com.spx.chapter09;

import com.spx.chapter05.pojo.Event;
import com.spx.util.ClickSource;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.Map;

/**
 * create by undeRdoG on  2022-05-05  22:45
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class FakeWindowByMapState {

    public static void main(String[] args) throws Exception {
        // 需求：按照url划分，统计10秒一个窗口被点击的次数
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<Event> stream = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.timestamp;
                                    }
                                })
                );

        stream.print("stream");

        stream.keyBy(data -> data.url)
                .process(new FakeWindowFunction(10000L))
                .print();
        env.execute();
    }

    public static class FakeWindowFunction extends KeyedProcessFunction<String,Event,String>{

        private Long windowSize;

        private MapState<Long,Long> windowUrlCountState;

        public FakeWindowFunction(Long windowSize) {
            this.windowSize = windowSize;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            this.windowUrlCountState = getRuntimeContext().getMapState(new MapStateDescriptor<Long, Long>("mapState", Long.class, Long.class));
        }

        @Override
        public void processElement(Event value, Context ctx, Collector<String> out) throws Exception {
            // 每来一条数据，根据数据判断属于哪个窗口
            Long windowStart = value.timestamp / this.windowSize * this.windowSize;

            Long windowEnd = windowStart + windowSize;

            // 注册定时器
            ctx.timerService().registerEventTimeTimer(windowEnd - 1L);

            // 更新状态
            Long windowState = this.windowUrlCountState.get(windowStart);
            if (windowState == null){
                windowUrlCountState.put(windowStart, 1L);
            }else{
                windowUrlCountState.put(windowStart, windowUrlCountState.get(windowStart) + 1L);
            }
        }


        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            Long windowEnd = timestamp + 1;
            Long windowStart = windowEnd - this.windowSize;
            Long count = this.windowUrlCountState.get(windowStart);

            out.collect(
                    "窗口" + new Timestamp(windowStart) + "~" + new Timestamp(windowEnd)
                    +" url is" + ctx.getCurrentKey()
                    +" count is " + count
            );

            // 模拟窗口关闭，清除对应窗口的state
            this.windowUrlCountState.remove(windowStart);
        }
    }

}
